package client;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import util.ChecksumHelper;
import util.SHAHelper;
import util.SerializationHelper;
import dataContracts.FileState;
import dataContracts.SharedFile;

public class ClientFile extends SharedFile {
	
	public ClientFile(String filePath) {
		this(new File(filePath));
	}
	
	public ClientFile(File file) {
		super(file);
	}
	
	// by default, assume it is synchronized
	public FileState fileState = FileState.Synchronized;
	
	public void Serialize() {
		File f = new File(this.getFullPath()+".ser");
		new SerializationHelper<ClientFile>().Serialize(this, f);
	}
	
	public ClientFile Deserialize() {
		File f = new File(this.getFullPath()+".ser");
		return new SerializationHelper<ClientFile>().Deserialize(f);
	}

	public boolean hasLocalChanges() {
		return !ChecksumHelper.GetChecksum(getFileReference()).equalsIgnoreCase(this.getChecksum());
	}
	
	public void refresh() {
		if (getFileReference().exists()) {
			String newChecksum = ChecksumHelper.GetChecksum(getFileReference());
			// mark if it has changed locally
			if (!newChecksum.equalsIgnoreCase(getChecksum())) {
				fileState = FileState.Updated;
				this.setChecksum(newChecksum);
			}
		} else {
			// mark for deletion
			fileState = FileState.Deleted;
		}
	}

	@Override public boolean equals(Object o) {
		// if it's an object of different type it's always false
		if (!(o instanceof ClientFile))
			return false;
		
		// cast the object to Rational
		ClientFile other = (ClientFile)o;
		// since the Rational is always reduced we can do this simple compare
		if (this.getChecksum().equals(other.getChecksum())) {
			return true;
		}
		
		return false;
	}
	
	// we must override this since we overrode equals above
	@Override public int hashCode() {
		// factor in each field used in the equals method
		return getChecksum().hashCode();
	}
}
